#include <iostream>
using namespace std;
#include <unistd.h>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include "log.hpp"
#include <netinet/in.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <functional>
#include <arpa/inet.h>

namespace Client
{
    class tcpClient
    {
    public:
        tcpClient(const string &ip, const uint16_t &port)
            : _sock(-1), _server_ip(ip), _server_port(port)
        {
        }

        void initClient()
        {
            _sock = socket(AF_INET, SOCK_STREAM, 0);
            if (_sock < 0)
            {
                logMessage(4, "socket errno");
                exit(1);
            }
            logMessage(1, "socket success");

            // 客户端由os自动连接
        }
        void start()
        {
            struct sockaddr_in server;
            socklen_t len = sizeof(server);
            server.sin_family = AF_INET;
            server.sin_port = htons(_server_port);
            server.sin_addr.s_addr = inet_addr(_server_ip.c_str());

            // 开始connect
            int n = connect(_sock, (sockaddr *)&server, len);
            if (n < 0)
            {
                logMessage(4, "connect errno");
                exit(2);
            }
            logMessage(1, "connect success");

            string line;
            while (1)
            {
                cout << "请输入#";
                getline(cin, line);

                write(_sock, line.c_str(), sizeof(line));

                char buffer[1024];
                ssize_t n = read(_sock, buffer, sizeof(buffer) - 1);
                if (n > 0)
                {
                    buffer[n] = 0;
                    cout << "server回显：" << buffer << endl;
                }
            }
        }

        ~tcpClient()
        {
            if (_sock)
                close(_sock);
        }

    private:
        int _sock;
        uint16_t _server_port;
        string _server_ip;
    };

}